package com.car.slave.im;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

import com.car.slave.im.model.IMMessage;
import com.car.slave.im.model.command.IMCommandMessage;
import com.car.slave.im.model.user.IMAudioMessage;
import com.car.slave.im.model.user.IMImageMessage;
import com.car.slave.im.model.user.IMTextMessage;
import com.car.slave.im.model.user.IMUserMessage;
import com.car.slave.im.receiver.IMLoginReceiver;
import com.car.slave.im.receiver.IMMessageReceiver;
import com.car.slave.im.receiver.IMNotificationReceiver;
import com.car.slave.im.util.IMTool;
import com.car.slave.im.util.QiuniuUtil.UploadFileCallback;

/**
 * 处理信息的读和写
 * @author zhangliucheng
 *
 */
public class IMProcessMessage {
	
	/**
	 * 发送信息.
	 * @param os
	 * @throws InterruptedException
	 * @throws IOException
	 */
	public static void processSendMessage(Context context, OutputStream os) throws InterruptedException, IOException {
		final IMMessage message = IMClient.shareInstance().getSendMessage(context);
		if (null != message) {
			if (message instanceof IMUserMessage) {
				sendUserMessage(context, os, (IMUserMessage) message);
			} else if (message instanceof IMCommandMessage) {
				sendCommandMessage(context, os, (IMCommandMessage) message);
			}
		} else {
//			os.write(new byte[]{0, 0, 0, 1});		// 发送心跳包
		}
	}

	// 发送用户信息， e.g:文字，图片，语音.
	private static void sendUserMessage(Context context, OutputStream os, IMUserMessage msg) throws IOException {
		if (msg instanceof IMTextMessage) {
			writeTextMessage(context, os, (IMTextMessage) msg);		
		} else if (msg instanceof IMImageMessage) {
			writeImageMessage(context, os, (IMImageMessage) msg);	
		} else if (msg instanceof IMAudioMessage) {
			writeAudioMessage(context, os, (IMAudioMessage) msg);	
		}
	}
	
	// 发送命令信息，e.g:登陆，登出.
	private static void sendCommandMessage(Context context, OutputStream os, IMCommandMessage msg) throws IOException {
		try {
			os.write(msg.getSendBuffer());
		} catch (IOException e) {
			throw e;
		}
	}
	
	// 文本消息
	private static void writeTextMessage(final Context context, final OutputStream os, final IMTextMessage txtMsg) {
		txtMsg.sentStatus = 2;					// 发送成功 		
		writeMessage(context, os, txtMsg);
	}
	
	// 图片消息
	private static void writeImageMessage(final Context context, final OutputStream os, final IMImageMessage imgMsg) {
		IMTool.uploadImage(context, imgMsg, new UploadFileCallback() {
			@Override
			public void uploadResult(boolean success, String url) {
				imgMsg.imageFileUrl = url;
				imgMsg.sentStatus = success ? 2 : 1;
				writeMessage(context, os, imgMsg);
			}
		});
	}
	
	// 语音消息
	private static void writeAudioMessage(final Context context, final OutputStream os, final IMAudioMessage audioMsg) {
		IMTool.uploadAudio(context, audioMsg, new UploadFileCallback() {
			@Override
			public void uploadResult(boolean success, String url) {
				System.out.println("url   " + url);
				audioMsg.audioFileUrl = url;
				audioMsg.sentStatus = success ? 2 : 1;
				writeMessage(context, os, audioMsg);
			}
		});
	}

	// 发送给服务端并且保存到数据库
	private static void writeMessage(Context context, OutputStream os, IMUserMessage msg) {
		try {
			os.write(msg.getSendBuffer());
		} catch (IOException e) {
			msg.sentStatus = 1; 			// 发送失败
		}
		IMMessageManager.shareInstance(context).saveMessage(context, msg);		// 保存到数据库
		IMMessageReceiver.postSendMessageResultBroadcast(context, msg);			// 发送信息成功/失败广播
	}
	
	/**
	 * 读取Service发来的信息.
	 * @param is
	 * @throws IOException
	 */
	public static void processReadMessage(Context context, byte[]headBuffer, InputStream is) throws IOException {
		if (null == headBuffer || headBuffer.length < 4) {
			return;
		}
		int len = IMTool.bufferToInt(new byte[]{headBuffer[0], headBuffer[1]}) - 6;
		int code = IMTool.bufferToInt(new byte[]{headBuffer[4], headBuffer[5]});
		
		byte[] contentBuf = new byte[len];
		DataInputStream dis = new DataInputStream(is);
		dis.readFully(contentBuf);

		// 如果读到的长度小于等于0，说明Service关闭了socket，抛出异常，让IMService断开连接，再重新连接Service
//		int rLen = is.read(contentBuf);
//		if (rLen <= 0) {
//			System.out.println("rLen  " + rLen);
//			throw new IOException("服务器断开连接");
//		}

		
		// TODO
//		for (int i = 0; i < contentBuf.length; i++) {
//			int b = is.read();
//			if (b < 0) {
//				throw new IOException("服务器断开连接");
//			}
//			contentBuf[i] = (byte)b;
//		}
		String content = new String(contentBuf, Charset.defaultCharset());
		
		
		System.out.println("len=" + len + ";code=" + code + ";content=" + content);

		// 和服务端验证登陆信息
		if (code == IMMessage.CMD_USER_LOGIN) {
			IMLoginReceiver.postLoginBroadcast(context, content);
			return;
		}
		// 异地登陆
		if (code == IMMessage.CMD_USER_KICK_USER_NOTIFY) {
			IMNotificationReceiver.postOtherLoginBroadcast(context);
			return;
		}
	    // 接收到新消息
		if (code == IMMessage.CMD_USER_CHAT_MSG) {
			IMProcessMessage.processServiceMessage(context, content);
			return;
		}
	    // 进入聊天框向服务器发送命令，服务器回复欢迎语
		if (code == IMMessage.CMD_USER_ENTER_CHAT_WINDOW) {
			IMProcessMessage.processWelcomeMessage(context, content);
		}
	}
	
	// 接收到客服消息
	private static void processServiceMessage(Context context, String content) {
		IMUserMessage message = jsonToUserMessage(content);
		if (null == message) {
			return;
		}
		// 没有打开推送，说明当前正在聊天界面，收到信息标示为已读
		if (!IMClient.shareInstance().isMessageNotification()) {
			message.markReadStatus();
		}
		// 当前打开推送
		if (IMClient.shareInstance().isMessageNotification()) {
			IMNotificationReceiver.postNotificaterBroadcast(context, message);		// 发送推送
		} else {
			IMMessageReceiver.postReceiveMessageBroadcast(context, message);		// 发送新消息通知
		}
		IMMessageManager.shareInstance(context).saveMessage(context, message);		// 保存到数据库
	}
	
	// 接收到welcome消息
	private static void processWelcomeMessage(Context context, String content) {
		IMTextMessage message = jsonWelcomeToMessage(content);
		if (null == message) {
			return;
		}
		message.markReadStatus();
		IMMessageReceiver.postReceiveMessageBroadcast(context, message);			// 发送新消息通知
		IMMessageManager.shareInstance(context).saveMessage(context, message);		// 保存到数据库
	}
	
	private static IMUserMessage jsonToUserMessage(String json) {
		IMUserMessage msg = null;
		try {
			JSONObject obj = new JSONObject(json);
			int type = obj.optInt("type");
			String msgId = obj.optString("msg_id");
			String content = obj.optString("content");
			String time = obj.optString("time");
			if (type == IMUserMessage.TYPE_IMAGE) {
				msg = new IMImageMessage(msgId, content);
			} else if (type == IMUserMessage.TYPE_VOICE) {
				msg = new IMAudioMessage(msgId, content);
			} else {
				msg = new IMTextMessage(msgId, content);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return msg;
	}
	
	private static IMTextMessage jsonWelcomeToMessage(String json) {
		IMTextMessage msg = null;
		try {
			JSONObject obj = new JSONObject(json);
			String content = obj.optString("welcome");
			msg = new IMTextMessage(IMUserMessage.getAutoMessageid(), content);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return msg;
	}
}
